package org.budo.html.editor.um.handler;

import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.html.editor.filter.BudoHtmlEditorFilter;
import org.budo.html.editor.handler.AbstractBudoHtmlEditorHandler;
import org.budo.support.java.net.util.UrlEncodeUtil;
import org.budo.support.lang.util.FileUtil;
import org.budo.support.lang.util.IoUtil;
import org.budo.support.lang.util.MapUtil;
import org.budo.support.mvcs.Mvcs;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;

/**
 * @author lmw
 */
public class UMEditorHandler extends AbstractBudoHtmlEditorHandler {
    @Override
    public Boolean handleRequest(HttpServletRequest request, HttpServletResponse response, BudoHtmlEditorFilter budoHtmlEditorFilter) {
        String requestUri = request.getRequestURI();

        if (!requestUri.contains("/um/")) {
            return false;
        }

        if (requestUri.contains("/um/imageUrl")) {
            this.imageUrl(request, response, budoHtmlEditorFilter);
        }

        if (requestUri.contains("/um/resources/")) {
            String resourceName = requestUri.replace("/budo-html-editor/um/resources/", "/META-INF/resources/um/");
            return this.writeClassPathResource(resourceName, response);
        }

        return true;
    }

    private void imageUrl(HttpServletRequest request, HttpServletResponse response, BudoHtmlEditorFilter budoHtmlEditorFilter) {
        MultipartFile multipartFile = this.getFirstMultipartFile(request);
        String url = budoHtmlEditorFilter.handleMultipartFile(multipartFile);

        Map<String, Object> resultMap = MapUtil.stringObjectMap("name", multipartFile.getName() //
                , "originalName", UrlEncodeUtil.encode(multipartFile.getOriginalFilename()) //
                , "size", multipartFile.getSize() //
                , "state", "SUCCESS"//
                , "type", "." + FileUtil.getSuffix(multipartFile.getOriginalFilename()) //
                , "url", url);
        String resultStr = JSON.toJSONString(resultMap);

        response.setContentType("text/html");
        ServletOutputStream outputStream = Mvcs.getResponseOutputStream(response);

        String callback = Mvcs.getRequestParameter("callback");
        if (callback == null) {
            IoUtil.write(resultStr, outputStream);
        } else {
            IoUtil.write("<script>" + callback + "(" + resultStr + ")</script>", outputStream);
        }
    }
}
